package org.xmppbot.net;

import org.junit.Test;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.filter.codec.*;

import java.net.InetSocketAddress;

/**
 * Comment here.
 * User: Bulat Nigmatullin
 * Date: 13.07.2009
 * Time: 18:28:07
 */
public class DialbackCheckServer {

    private static final int PORT = 5269;

    @Test
    public void test() throws Exception {
        IoAcceptor acceptor = new NioSocketAcceptor();
        acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ProtocolCodecFactoryImpl()));
        acceptor.setHandler(new DialbackHandler());
        acceptor.bind(new InetSocketAddress(PORT));

        Thread.sleep(60000);
        acceptor.unbind();
    }

    private class DialbackHandler extends IoHandlerAdapter {

        @Override
        public void sessionOpened(IoSession ioSession) throws Exception {
            System.out.println("sessionOpened");
        }

        @Override
        public void sessionCreated(IoSession ioSession) throws Exception {
            System.out.println("sessionCreated");
        }

        @Override
        public void sessionClosed(IoSession ioSession) throws Exception {
            System.out.println("sessionClosed");
        }

        @Override
        public void messageReceived(IoSession ioSession, Object o) throws Exception {
            System.out.println("messageReceived " + o);
        }
    }

    private class ProtocolCodecFactoryImpl implements ProtocolCodecFactory {

        @Override
        public ProtocolEncoder getEncoder(IoSession ioSession) throws Exception {
            return null;
        }

        @Override
        public ProtocolDecoder getDecoder(IoSession ioSession) throws Exception {
            return new ProtocolDecoderImpl();
        }
    }

    private class ProtocolDecoderImpl implements ProtocolDecoder {

        @Override
        public void decode(IoSession ioSession, IoBuffer ioBuffer, ProtocolDecoderOutput protocolDecoderOutput) throws Exception {
            StringBuffer buffer = new StringBuffer();
            while (ioBuffer.hasRemaining()) {
                buffer.append((char)ioBuffer.get());
            }
            protocolDecoderOutput.write(buffer.toString());
        }

        @Override
        public void finishDecode(IoSession ioSession, ProtocolDecoderOutput protocolDecoderOutput) throws Exception {
        }

        @Override
        public void dispose(IoSession ioSession) throws Exception {
        }
        
    }

}
